#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json
import os
import stat
import uuid

from clickhouse import log
from common.common_models import LogDetail, SubJobDetails

from clickhouse.common.clickhouse_constants import AgentConstant, PluginPathConstant
from common.common import execute_cmd, write_content_to_file
from common.util.cmd_utils import cmd_format


def get_agent_id():
    """
    功能描述：获取Agent ID
    参数：无
    返回值：Agent ID
    """
    agent_file_path = AgentConstant.HOST_SN_FILE_PATH
    if not agent_file_path or not os.path.exists(agent_file_path):
        return ""
    with open(agent_file_path, "r", encoding="utf-8") as f:
        text = f.read()
    return text.strip("\n")


def report(backup_tables_len, i, pid, job_id, **kwargs):
    """
    功能描述：上报进度
    参数：
    @backup_tables_len： 备份表的个数
    @i： 第i张表
    @backup_table： 备份的表名
    @task_progress： 进度
    @kwargs： 参数map
    """
    task_progress = 100
    if backup_tables_len > 0:
        task_progress = int(i * 100 / backup_tables_len)
    log_detail = LogDetail(logInfo=kwargs.get('log_info'), logInfoParam=kwargs.get('logInfoParam'),
                           logLevel=kwargs.get('log_level'))
    report_job_details(pid, SubJobDetails(taskId=job_id, progress=task_progress, logDetail=[log_detail],
                                          taskStatus=kwargs.get('task_status')))


def report_job_details(pid, job_detail):
    """
    功能描述：上报进度
    参数：无
    @pid: pid
    @job_detail: 任务详情
    返回值：无
    """
    random_id = f'clickhouse_{pid}_' + str(uuid.uuid4())
    input_file = PluginPathConstant.TMP_PATH.value + random_id + '_input'
    output_file = PluginPathConstant.TMP_PATH.value + random_id + '_output'
    json_str = json.dumps(job_detail.dict(by_alias=True))
    write_content_to_file(input_file, json_str)

    cmd = cmd_format('sh {}rpctool.sh ReportJobDetails {} {}', PluginPathConstant.DB_BIN_PATH.value, input_file,
                     output_file)
    code, out, err = execute_cmd(cmd)
    log.info(f'report_job_details, code: {code}, out: {out}, err: {err}')
    with open(output_file, 'r', encoding='utf-8') as file_read:
        log.info(f'{pid} report result: {file_read.readlines()}')
    os.remove(input_file)
    os.remove(output_file)


def get_dir_size(path):
    lst = os.listdir(path)
    size = 0
    for i in lst:
        path_new = os.path.join(path, i)
        if os.path.isfile(path_new):
            size += os.path.getsize(path_new)
        elif os.path.isdir(path_new):
            size += get_dir_size(path_new)
    return size


def compute_size(total_size, i=None):
    if i is None:
        i = 1
    unit = AgentConstant.UNITS[i]
    while total_size > 1024 and i < 9:
        total_size /= 1024
        i += 1
        unit = AgentConstant.UNITS[i]
    return str(str(round(total_size, AgentConstant.THREE_DECIMAL_PLACES)) + " " + unit)
